package benny.ApkposStore.Activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import benny.ApkposStore.R;
import benny.ApkposStore.R.string;
import benny.ApkposStore.Adapter.dishpotlistAdapter;
import benny.ApkposStore.Adapter.dishpotlistAdapter.Dishpotlistholder;
import benny.ApkposStore.db.DBHelper;
import benny.ApkposStore.model.DishNew;
import benny.ApkposStore.model.OrderNew;
import benny.ApkposStore.utils.ApkDbUntils;
import benny.ApkposStore.utils.ApkUntils;
import benny.ApkposStore.utils.Apkglobal;
import benny.ApkposStore.utils.Rotate3dAnimation;

//import com.tencent.elife.asyn.BaseManager;
//import com.tencent.elife.asyn.Command;
//import com.tencent.elife.asyn.DataResponse;

public class SetupdishActivity extends Activity {

	private String room_name;
	private String room_id;
	private String orderid;
	private int peoplenum;

	@Override
	protected void onDestroy() {
		System.gc(); // 回收系统资源
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private int cooklistview_height;
	private Resources resources;
	private Button cookviewclose;
	private Button cookviewbtn1;
	private Button cookviewbtn2;
	private Button cookviewbtn3;
	private Button cookviewbtn4;
	private GridView powgridView;
	private EditText dishcountchange;
	private ListAdapter menuAdapter;
	private ListView setupdishlistView;
	private int dishpotlist_heightdip;
	private int dishpotlist_heightpx = 25;
	private List<DishNew> dishlist;
	private dishpotlistAdapter dishpotlistAdapter;
	private boolean keydown;
	private ArrayList<OrderNew> orderlist;
	private OrderNew ordermain;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		ApkUntils.fullscreen(this);
		setContentView(R.layout.dishview);
		keydown = false;	
		menuAdapter = ApkUntils.getMenuAdapter(this);
		// DataManager.instance().init(getApplicationContext());
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();// 根据bundle的key得到对应的对象
		room_name = bundle.getString("room_name");
		room_id = bundle.getString("room_id");
		orderid = bundle.getString("orderid");
		peoplenum = bundle.getInt("people_num");

		TextView roomname = (TextView) findViewById(R.id.roomtext);
		TextView people = (TextView) findViewById(R.id.peoplenumtext);
		TextView ordersid = (TextView) findViewById(R.id.ordersid);

		roomname.setText(room_name);
		ordersid.setText("NO." + orderid);
		people.setText(peoplenum + "");
		setupdishlistView = (ListView) findViewById(R.id.setupdishlistview);

		dishpotlist_heightdip = ApkUntils.convertPX2DIP(this,
				dishpotlist_heightpx);
		resources = getResources();
		setupdishlistView.setDivider(resources.getDrawable(R.color.white));
		setupdishlistView.setDividerHeight(ApkUntils.convertPX2DIP(this, 1));
		setupdishlistView.setSelector(R.color.transparent);

		// 加载数据
		showsetupdishlist(1);
		setupdishlistView
				.setOnItemClickListener(new setupdishlistViewListener());
		cookviewclose = (Button) findViewById(R.id.cookviewclose); // 取得组件
		cookviewclose.setTag(10);
		cookviewbtn1 = (Button) findViewById(R.id.cookviewbtn1); // 取得组件
		cookviewbtn1.setTag(1);
		cookviewbtn2 = (Button) findViewById(R.id.cookviewbtn2); // 取得组件
		cookviewbtn2.setTag(2);
		cookviewbtn3 = (Button) findViewById(R.id.cookviewbtn3); // 取得组件
		cookviewbtn3.setTag(3);
		cookviewbtn4 = (Button) findViewById(R.id.cookviewbtn4); // 取得组件
		cookviewbtn4.setTag(4);
		cookviewbtn1.setOnClickListener(new dishbtnListener());
		cookviewbtn2.setOnClickListener(new dishbtnListener());
		cookviewbtn3.setOnClickListener(new dishbtnListener());
		cookviewbtn4.setOnClickListener(new dishbtnListener());
		cookviewclose.setOnClickListener(new dishbtnListener());

		powgridView = (GridView) findViewById(R.id.gridview_softkeyboard);
		dishcountchange = (EditText) findViewById(R.id.dishcountchange);
		ordermain = ApkDbUntils
				.queryorder(getApplicationContext(), orderid);
		dishcountchange.setText(ordermain.getDic_rate() + "");
		dishcountchange.setTag(1);
		// ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
		// .hideSoftInputFromWindow(getCurrentFocus()
		// .getWindowToken(),
		// InputMethodManager.HIDE_NOT_ALWAYS);
		// dishcountchange.setInputType(InputType.TYPE_CLASS_NUMBER);
		dishcountchange.setInputType(InputType.TYPE_NULL);
		// dishcountchange.setOnClickListener(new c)

		// dishcountchange.setCursorVisible(true);
		dishcountchange.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				// m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				m.hideSoftInputFromWindow(SetupdishActivity.this
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				// ApkUntils.closeSystemKeyBoard(getApplicationContext(),
				// dishcountchange);
			}
		});

		dishcountchange.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					dishcountchange.selectAll();
					// dishcountchange.setSelectAllOnFocus(true);
					break;
				case MotionEvent.ACTION_UP:
					// dishcountchange.setInputType(InputType.TYPE_CLASS_NUMBER);
					ApkUntils.opensoftkeyboard(dishcountchange, powgridView,
							menuAdapter, 1);
					ApkUntils.keyboardtouchup(dishcountchange, powgridView,
							menuAdapter, getApplicationContext());
					ApkUntils.closeSystemKeyBoard(getApplicationContext(),
							dishcountchange);
					break;
				default:
					break;
				}

				return false;
			}
		});

	}

	// 创建扩展菜品界面功能按钮事件
	class dishbtnListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final int tag = (Integer) v.getTag();

			Rotate3dAnimation rotation = new Rotate3dAnimation(0, 90,
					v.getWidth() / 2.0f, v.getHeight() / 2.0f, 300.0f, false);
			rotation.setDuration(500);
			// rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());
			v.setAnimation(rotation);
			v.startAnimation(rotation);
			rotation.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation animation) {
					// TODO Auto-generated method stub
					System.out.println("aaaa" + tag);
					switch (tag) {
					case 1:

						ApkDbUntils.deletedishall(getApplicationContext(),
								orderid);
						finish();

						break;
					case 2:

						ApkDbUntils.holdbill( getApplicationContext(),
								orderid);
						Intent intent = new Intent();
						intent.setClass(SetupdishActivity.this,
								RoomtableActivity.class);
						startActivity(intent);
						ApkUntils.openActivityAnim(SetupdishActivity.this, 0);
						finish();
						break;
					case 3:
						orderlist = ApkDbUntils.checkbill(
								getApplicationContext());

						break;
					case 4:// 设置按钮

						String str = dishcountchange.getText().toString();

						float d = Float.parseFloat(str);
						if (d < 0) {
							Toast.makeText(SetupdishActivity.this,
									"折扣不能小于0,请重新设置！", Toast.LENGTH_SHORT)
									.show();
							dishcountchange.setText("0");
							ApkUntils.opensoftkeyboard(dishcountchange,
									powgridView, menuAdapter, 1);
						} else if (d > 100) {
							Toast.makeText(SetupdishActivity.this,
									"折扣不能大于100,请重新设置！", Toast.LENGTH_SHORT)
									.show();
							dishcountchange.setText("100");
							ApkUntils.opensoftkeyboard(dishcountchange,
									powgridView, menuAdapter, 1);

						} else {
							ApkDbUntils.setupbill( getApplicationContext(),
									orderid, str);
							finish();
						}

						break;

					case 10:
						finish();
						break;

					default:
						break;
					}
				}

			});

		}
	}

	private void showsetupdishlist(int flag) {
		dishlist = ApkDbUntils.updatedishlist(getApplicationContext(),
				orderid);
		dishpotlistAdapter = new dishpotlistAdapter(this, dishlist);
		if (Apkglobal.getcurrentapiVersion() > 10) {
			setupdishlistView.setAdapter(dishpotlistAdapter);
		}
		if (flag == 1) {
			if (dishpotlistAdapter.getCount() == 0) {
				ApkUntils.changeviewlayout(setupdishlistView, 0, 1,
						dishpotlistAdapter);
			} else {
				cooklistview_height = dishpotlist_heightdip
						* dishpotlistAdapter.getCount();
				ApkUntils.changeviewlayout(setupdishlistView, 0,
						cooklistview_height, dishpotlistAdapter);
			}
		}

	}

	// 创建setupdishlistView按下监听事件
	class setupdishlistViewListener implements OnItemClickListener {

		private Dishpotlistholder dishpotlistholder = null;
		private float dishnum = 0;
		private String orderflag;
		private String dishid;

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			dishpotlistholder = (Dishpotlistholder) view.getTag();
			dishnum = Float.parseFloat(dishpotlistholder.dishitem3.getText()
					.toString());
			orderflag = dishpotlistholder.dishitem6.getText().toString();
			dishid = dishpotlistholder.dishid;
			dishpotlistholder.dishitem11
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (keydown) {
								return;
							}
								try {
									keydown = true;
									dishnum = addclick(orderflag, dishid, dishnum);
									dishpotlistholder.dishitem11.startchange();
									if (!orderflag.equals("√")) {
										// finish();
										dishpotlistholder.dishitem3.setText(dishnum
												+ "");
									}
									keydown = false;	
								} catch (Exception e) {
									// TODO: handle exception
									keydown = false;	
								}
							
						}
					});

			dishpotlistholder.dishitem12
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							if (keydown) {
								return;
							}
							try {
								keydown = true;
								dishnum = delclick(orderflag, dishid, dishnum);
								dishpotlistholder.dishitem12.startchange();
								if (!orderflag.equals("√")) {
									if (dishnum == 0) {
										showsetupdishlist(1);
									} else {
										dishpotlistholder.dishitem3
												.setText(dishnum + "");
									}
									// finish();

								}
								keydown = false;	
							} catch (Exception e) {
								// TODO: handle exception
								keydown = false;	
							}
								
							
							/*
							 * Toast.makeText(DishordersActivity.this, "点击了第" +
							 * aaa + "减1按钮", Toast.LENGTH_SHORT) .show();
							 */
						}
					});

		}
	}

	// 加菜函数(未落单)
	private float addclick(String flag, final String dishid, float old_num) {

		SQLiteDatabase db = DBHelper.getWritableDatabase(getApplicationContext());
	
		Cursor cursor = db.query("apkpos_orders_dishs",
				new String[] { "ifnull(dish_num,0) as aaa" },
				"orderid=? and dish_id=?", new String[] { orderid, dishid },
				null, null, null);
		while (cursor.moveToNext()) {
			old_num = cursor.getFloat(cursor.getColumnIndex("aaa"));

		}
		cursor.close();
		db.close();
		db=null;
		if (flag.equals("√")) {

			Builder builder = new Builder(this);
			String quitMsg = "已经传到厨房,确定要进行加菜操作吗？";
			builder.setMessage(quitMsg);
			builder.setTitle(string.dialog_title1);
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setPositiveButton(string.ok,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							ApkDbUntils.changedishnum(
									getApplicationContext(), "add", 1, orderid,
									dishid);
							showsetupdishlist(1);
							// finish();
							Toast.makeText(SetupdishActivity.this, "增加份量成功！",
									Toast.LENGTH_SHORT).show();
						}

					});
			builder.setNegativeButton(string.cancal,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}

					});

			builder.create().show();

		} else {

			ApkDbUntils.changedishnum( getApplicationContext(), "add", 1,
					orderid, dishid);
			// finish();

			Toast.makeText(SetupdishActivity.this, "增加份量成功！",
					Toast.LENGTH_SHORT).show();

		}
		old_num = old_num + 1;
		return old_num;

	}

	// 减菜函数(已落单)
	private float delclick(String flag, final String dishid, float old_num) {

		SQLiteDatabase db = DBHelper.getReadableDatabase(getApplicationContext());

		Cursor cursor = db.query("apkpos_orders_dishs",
				new String[] { "ifnull(dish_num,0) as aaa" },
				"orderid=? and dish_id=?", new String[] { orderid, dishid },
				null, null, null);
		
		while (cursor.moveToNext()) {
		   
			old_num = cursor.getFloat(cursor.getColumnIndex("aaa"));
		}
		cursor.close();
		db.close();
		db=null;
		final float num = old_num - 1;
		if (num < 0) {
			Toast.makeText(SetupdishActivity.this, "当前份量已经为零，无法减菜！",
					Toast.LENGTH_SHORT).show();
			return num;
		} else {
			if (flag.equals("√")) {

				Builder builder = new Builder(this);
				String quitMsg = "已经传到厨房,确定要进行减菜操作吗？";
				builder.setMessage(quitMsg);
				builder.setTitle(string.dialog_title1);
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setPositiveButton(string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								ApkDbUntils.changedishnum(
										getApplicationContext(), "del", 1,
										orderid, dishid);
								showsetupdishlist(1);
								// showdishlist();
								Toast.makeText(SetupdishActivity.this,
										"减少份量成功！", Toast.LENGTH_SHORT).show();
								
							}

						});

				builder.setNegativeButton(string.cancal,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}

						});

				builder.create().show();

			} else {

				if (old_num <= 1) {
					ApkDbUntils.deletedish( getApplicationContext(),
							orderid, dishid);
					// old_num = 0;
				} else {
					ApkDbUntils.changedishnum(getApplicationContext(),
							"del", 1, orderid, dishid);

					Toast.makeText(SetupdishActivity.this, "减少份量成功！",
							Toast.LENGTH_SHORT).show();

				}
			}
		}

		old_num = old_num - 1;
		return old_num;

	}

}
